const cleanIp = (ip) => {
  if (!ip) return null;
  
  let cleanIp = ip.trim();
  
  // 处理特殊地址
  if (cleanIp === "::1" || cleanIp === "localhost") {
    return "127.0.0.1";
  }
  
  // 处理 IPv6 格式的地址 (::ffff:192.168.1.1)
  if (cleanIp.includes("::ffff:")) {
    cleanIp = cleanIp.replace("::ffff:", "");
  }
  
  // 移除端口号（如果有）
  if (cleanIp.includes(":")) {
    const parts = cleanIp.split(":");
    cleanIp = parts[0];
  }
  
  return cleanIp;
};

const getRealClientIp = (req) => {
  // Cloudflare 真实IP获取优先级
  // 1. CF-Connecting-IP (Cloudflare 专用)
  // 2. X-Forwarded-For (标准代理头)
  // 3. X-Real-IP (Nginx 等常用)
  // 4. Express 内置 ip 属性
  // 5. 连接信息
  
  let ip = 
    req.headers["cf-connecting-ip"] ||      // Cloudflare 专用头
    req.headers["x-forwarded-for"] ||       // 标准代理头
    req.headers["x-real-ip"] ||            // Nginx 等常用
    req.ip ||                              // Express 内置
    req.connection?.remoteAddress ||        // 连接信息
    req.socket?.remoteAddress;             // Socket 信息

  // 如果是多个IP，取第一个（通常是真实客户端IP）
  if (ip && ip.includes(",")) {
    ip = ip.split(",")[0].trim();
  }

  // 清理IP地址
  ip = cleanIp(ip);

  return ip;
};

const validateIp = (ip) => {
  // 如果是空值，返回 false
  if (!ip) return false;

  // 处理特殊地址
  if (ip === "::1" || ip === "localhost" || ip === "127.0.0.1") {
    return true;
  }

  // 清理IP地址，移除可能的端口号和其他无效字符
  let cleanIp = ip.trim();
  
  // 移除端口号（如果有）
  if (cleanIp.includes(":")) {
    const parts = cleanIp.split(":");
    cleanIp = parts[0];
  }

  // IPv4 地址验证
  const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
  if (!ipv4Regex.test(cleanIp)) {
    return false;
  }

  const parts = cleanIp.split(".");
  return parts.every((part) => {
    const num = parseInt(part, 10);
    return num >= 0 && num <= 255;
  });
};

export { validateIp, cleanIp, getRealClientIp };
